package inv.stask.logic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class  WriterUtil {
	
	protected abstract String getFilename();
	protected abstract String getLockFilename();
	
	public static final SimpleDateFormat sdf			= new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	public static final SimpleDateFormat shortFormat	= new SimpleDateFormat("MMM dd");
	public static final SimpleDateFormat dayFormat		= new SimpleDateFormat("dd");
	
	protected void write(Object tasks){
		synchronized (tasks.getClass()) {
			if(lockTasks()){
				writeTasks(tasks);
				removeLock();
			}
		}
	}
	
	protected Object read(){
		synchronized (WriterUtil.class) {
			if(lockTasks()){
				Object obj = readTasks();
				removeLock();
				
				return obj;
			}
		}
		
		return null;
	}
	

	
	private void writeTasks(Object tasks){
		FileOutputStream fos		= null;
		ObjectOutputStream oos		= null;
		
		try{
			fos		= new FileOutputStream(getFilename());
			oos		= new ObjectOutputStream(fos);
			
			oos.writeObject(tasks);
			
			oos.close();
		}catch(IOException io){
			System.err.println("WriterUtil.writeTasks() Fail writing tasks.");
			io.printStackTrace();
		}
	}
	
	private Object readTasks(){
		FileInputStream fis		= null;
		ObjectInputStream ois	= null;
		Object obj			= null;
		
		try{
			fis		= new FileInputStream(getFilename());
			ois		= new ObjectInputStream(fis);
			
			obj		=  ois.readObject();
			
			ois.close();
		}catch(Exception io){
			System.err.println("WriterUtil.writeTasks() Fail reading tasks.");
			io.printStackTrace();
		}
		
		return obj;
	}
	
	private boolean lockTasks(){
		File f	= new File(getLockFilename());
		if(f.exists()){
			System.err.println("WriterUtil.lockTasks() File locked.");
			return false;
		}
		
		try{
			FileWriter fw	= new FileWriter(f);
			fw.write("locked at " + sdf.format(new Date()));
			fw.close();
		}catch(Exception ex){
			f.delete();
			System.err.println("WriterUtil.lockTasks() Fail locking.");
			return false;
		}
		
		return true;
	}
	
	private boolean removeLock(){
		File f	= new File(getLockFilename());
		if(!f.exists()){
			System.err.println("WriterUtil.removeLock() No lock to remove.");
			return false;
		}
		
		f.delete();
		if(f.exists()){
			System.err.println("WriterUtil.removeLock() Fail to remove lock.");
			return false;
		}
		
		return true;
	}
	
}
